package com.kepler.social.web.controller;

import com.kepler.social.dao.domain.UserBaseInfo;
import com.kepler.social.service.manager.UserEmailManager;
import com.kepler.social.service.manager.UserManager;
import com.kepler.social.usersecurity.dao.domain.UserEmail;
import com.kepler.social.core.sharding.DatasourceType;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sharding")
public class ShardingController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShardingController.class);

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserEmailManager userEmailManager;


    @RequestMapping(value = "/user-email-insert")
    public int solial_user_email_inset(String email, Long userId) {
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setDatabaseShardingValue(DatasourceType.DATASOURCE_USER_SECURITY.toString());
            UserEmail userEmail = new UserEmail();
            userEmail.setEmail(email);
            userEmail.setUserId(userId);
            userEmail.setCreatedTime(System.currentTimeMillis());
            userEmail.setDisuseTime(0L);
            userEmail.setState(0);
            userEmail.setModifiedTime(0L);
            int r = userEmailManager.save(userEmail);
            return r;
        }
    }

    @RequestMapping(value = "/user-insert")
    public int solial_user_inset(Long id, String name) {
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setDatabaseShardingValue(DatasourceType.DATASOURCE_SOCAIL.toString());
            UserBaseInfo userBaseInfo = new UserBaseInfo();
            userBaseInfo.setId(id);
            userBaseInfo.setNickName(name);
            int r = userManager.insert(userBaseInfo);
            return r;
        }
    }

    @RequestMapping(value = "/user-get")
    public UserBaseInfo solial_user_get(Long id, String wr) {
//        return new UserBaseInfo();
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setDatabaseShardingValue(DatasourceType.DATASOURCE_SOCAIL.toString());
            if(wr.equals("W")){
               hintManager.setWriteRouteOnly();
            }
            UserBaseInfo userBaseInfo = userManager.getById(id);
            return userBaseInfo;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

}
